Python实现Hangman游戏

56次阅读
没有评论

共计 1310 个字符,预计需要花费 4 分钟才能阅读完成。

Hangman 游戏

Hangman 直译为“上吊的人”,是一个猜单词的双人游戏。由一个玩家想出一个单词或短语,另一个玩家猜该单词或短语中的每一个字母。第一个人抽走单词或短语,只留下相应数量的空白与下划线。

hangman_words.py

word_list = ["ardvark", "baboon", "camel"]

hangman_art.py

stages = [
    r"""
  +---+
  |   |
  O   |
 /|  |
 /   |
      |
=========
""",
    r"""
  +---+
  |   |
  O   |
 /|  |
 /    |
      |
=========
""",
    r"""
  +---+
  |   |
  O   |
 /|  |
      |
      |
=========
""",
    r"""
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========""",
    r"""
  +---+
  |   |
  O   |
  |   |
      |
      |
=========
""",
    r"""
  +---+
  |   |
  O   |
      |
      |
      |
=========
""",
    r"""
  +---+
  |   |
      |
      |
      |
      |
=========
""",
]

logo = r"""
 _
| |
| |__   __ _ _ __   __ _ _ __ ___   __ _ _ __
| '_  / _` |'_  / _` | '_ ` _  / _` |'_ 
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|__,_|_| |_|__, |_| |_| |_|__,_|_| |_|
                    __/ |
                   |___/
"""

main.py

import random
from hangman_art import logo, stages
from hangman_words import word_list

chosen_word = random.choice(word_list)
word_length = len(chosen_word)
end_of_game = False
lives = 6

print(logo)

## Create blanks
display = []
for _ in range(word_length):
    display += "_"

while not end_of_game:
    guess = input("Guess a letter: ").lower()

    if guess in display:
        print(f"You've already guessed {guess}")
        continue

    # Check guessed letter
    for position in range(word_length):
        letter = chosen_word[position]
        if letter == guess:
            display[position] = letter

    # Check if user is wrong.
    if guess not in chosen_word:
        print(f"You guessed {guess}, that's not in the word. You lose a life.")
        lives -= 1

    # Join all the elements in the list and turn it into a string.
    print(f"{' '.join(display)}")

    print(stages[lives])

    if "_" not in display:
        end_of_game = True
        print("You win!")

    if lives == 0:
        end_of_game = True
        print("You lose.")

正文完
 0
三毛笔记
版权声明:本站原创文章,由 三毛笔记 于2023-08-01发表,共计1310字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)